﻿using System;
using System.Collections.Generic;
using System.Timers;
using MySql.Data.MySqlClient;
using Microsoft.Extensions.Configuration;

namespace DataFetchingApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 读取配置文件
            var configuration = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .Build();

            // 获取配置信息
            string username = configuration["LoginSettings:Username"];
            string password = configuration["LoginSettings:Password"];
            string dbConnectionString = configuration.GetConnectionString("MySqlConnection");

 
            await ExecuteDataFetching(username, password, dbConnectionString);

            Console.WriteLine("定时任务已启动，每半个小时抓取一次数据...");
            Console.ReadLine(); // 保持程序运行，防止退出
        }

        static async Task ExecuteDataFetching(string username, string password, string dbConnectionString)
        {
            var dataFetcher1 = new DataFetcherImpl();
            dataFetcher1.GetTimedData();
            return;



            // 登录
            var loginService = new LoginServiceImpl();
            string token = await loginService.LoginAsync(username, password);

            // 抓取设备列表
            var dataFetcher = new DataFetcherImpl();
            List<Device> devices = await dataFetcher.FetchDeviceListAsync(token);

            // 获取上次抓取时间（假设从数据库中读取，这里先简单设为 null）
            DateTime? lastFetchTime = GetLastFetchTimeFromDb(dbConnectionString);

            // 抓取实时数据
            List<int> deviceAddrs = devices.Select(d => d.DeviceAddr).ToList();
            List<RealtimeData> realtimeData = await dataFetcher.FetchRealtimeDataAsync(token, deviceAddrs, lastFetchTime);

            // 存储数据
            var dataStorer = new MySqlDataStorer(dbConnectionString);
            int deviceCount = await dataStorer.StoreDevicesAsync(devices);
            int realtimeCount = await dataStorer.StoreRealtimeDataAsync(realtimeData);

            Console.WriteLine($"成功存储 {deviceCount} 条设备信息和 {realtimeCount} 条实时数据");

            // 记录本次抓取时间
            SaveCurrentFetchTimeToDb(dbConnectionString);
        }

        static DateTime? GetLastFetchTimeFromDb(string dbConnectionString)
        {
            using var connection = new MySqlConnection(dbConnectionString);
            connection.Open();
            string sql = "SELECT MAX(fetch_time) FROM fetch_records";
            using var cmd = new MySqlCommand(sql, connection);
            var result = cmd.ExecuteScalar();
            if (result != null)
            {
                return (DateTime)result;
            }
            return null;
        }

        static void SaveCurrentFetchTimeToDb(string dbConnectionString)
        {
            using var connection = new MySqlConnection(dbConnectionString);
            connection.Open();
            string sql = "INSERT INTO fetch_records (fetch_time) VALUES (@fetchTime)";
            using var cmd = new MySqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@fetchTime", System.DateTime.Now);
            cmd.ExecuteNonQuery();
        }
    }
}